import entity.User;

import java.util.*;

/**
 * @Version :
 * @PROJECT_NAME: java-basics
 * @PACKAGE_NAME:PACKAGE_NAME
 * @NAME: TreeSetExample
 * @author:xuandian
 * @DATE: 2022/6/25 10:30
 * @description:
 */

public class TreeSetExample {

    private Set<User> set = new TreeSet<>();

    /**
     * 排序
     * @param users
     * @return
     */
    User[] sort(User[] users) {
        set = new TreeSet<User>(new Comparator<User>() {
            @Override
            public int compare(User o1, User o2) {
                return o1.getUserId().compareTo(o2.getUserId());
            }

        });
        set.addAll(Arrays.asList(users));
        for (User user : set) {
            System.out.println(user);
        }
        return users;
    }

    /**
     * 添加
     * @param user
     * @return
     */
    boolean add(User user) {
        return set.add(user);
    }

    /**
     * 删除
     * @param user
     */
    boolean remove(User user) {
        return set.remove(user);
    }

    /**
     * 判断是否存在
     * @param user
     * @return
     */
    boolean contains(User user) {
        return set.contains(user);
    }

    /**
     * set转数组
     * @return
     */
    User[] toArray() {
        return set.toArray(new User[set.size()]);
    }
    public static void main(String[] args) {
        //初始化数据
        User uO = new User(3, "小王");
        User uT = new User(1, "小于");
        User uTh = new User(2, "小马");
        User uF = new User(4, "小刘");
        User[] users = new User[]{uO, uT, uTh,uF};
        //创建对象调用对应方法
        TreeSetExample treeSetExample = new TreeSetExample();
        System.out.println("排序");
        treeSetExample.sort(users);
        System.out.println("****************************");
        if (treeSetExample.add(new User(5, "小徐"))) {
            System.out.println("添加成功");
        }
        System.out.println("****************************");
        if (treeSetExample.remove(uO)) {
            System.out.println("移除成功"+uO);
        }
        System.out.println("****************************");
        if (treeSetExample.contains(uT)) {
            System.out.println("存在"+uT);
        }

        System.out.println("set集合转为数组");
        for (User user : treeSetExample.toArray()) {
            System.out.println(user);
        }
    }
}

